import React from "react";
import { RootProviderProps } from "./types";
import { RootDispatchContext, RootStateContext } from "./context";
import { INITIAL_STATE } from "./constants";
import { reducer } from "./reducer";
import { LoadingModal } from "../Loading";
import { useDispatch } from "./useDispatch";

const Init = React.memo(
  ({
    setLoading,
  }: {
    setLoading: React.Dispatch<React.SetStateAction<boolean>>;
  }) => {
    const { refreshUserInfo } = useDispatch();

    React.useEffect(() => {
      refreshUserInfo().finally(() => {
        setLoading(false);
      });
    }, [refreshUserInfo, setLoading]);
    return null;
  }
);

const RootProviderComponent: React.FC<RootProviderProps> = ({ children }) => {
  const [state, dispatch] = React.useReducer(reducer, INITIAL_STATE);
  const [loading, setLoading] = React.useState(true);

  return (
    <RootDispatchContext.Provider value={dispatch}>
      <RootStateContext.Provider value={state}>
        <Init setLoading={setLoading} />
        {loading ? <LoadingModal color="#fff" size={100} /> : children}
      </RootStateContext.Provider>
    </RootDispatchContext.Provider>
  );
};

const RootProvider = React.memo(RootProviderComponent);
RootProvider.displayName = "RootProvider";

export { RootProvider };
